package com.hcc.flow.server.controller.sys;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.annotation.Original;
import com.hcc.flow.server.common.constant.Constant;
import com.hcc.flow.server.common.enums.DataStatusType;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.page.table.PageTableHandler;
import com.hcc.flow.server.common.page.table.PageTableRequest;
import com.hcc.flow.server.common.page.table.PageTableResponse;
import com.hcc.flow.server.common.utils.CommUtil;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dao.sys.DepDao;
import com.hcc.flow.server.dao.sys.OrgDao;
import com.hcc.flow.server.dao.sys.RoleDao;
import com.hcc.flow.server.dao.sys.UserDao;
import com.hcc.flow.server.model.common.KeyIdName;
import com.hcc.flow.server.model.common.LoginUser;
import com.hcc.flow.server.model.sys.Org;
import com.hcc.flow.server.service.sys.OrgService;
import com.hcc.flow.server.service.sys.UserService;
import com.hcc.flow.server.utils.CheckIdUtil;
import com.hcc.flow.server.utils.UserUtil;
import com.hcc.flow.server.vo.sys.OrgOneVO;
import com.hcc.flow.server.vo.sys.OrgVO;
import com.hcc.flow.server.where.sys.OrgWhere;

import io.swagger.annotations.ApiOperation;
/**
 * 机构广告
 * @author 韩长志 2019-11-19
 *
 */
@RestController
@RequestMapping("/orgs")
public class OrgController {

	@Autowired
	private OrgDao orgDao;
	@Autowired
	private OrgService orgService;
	@Autowired
	private DepDao depDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserService userService;
	
	@GetMapping("/listAll")
	@ApiOperation(value = "机构-所有机构列表")
	/*//@PreAuthorize("hasAuthority('sys:org:query')")*/
	public List<OrgVO> List() {
		String userId = UserUtil.getLoginUser().getUserId();
		if(Constant.SYSTEM_MANAGE_TOP_USER_IDS.contains(userId) 
				|| userDao.getPermissionByPermAndUserId(userId, "sys:org:add") > 0) {
			OrgWhere strCon = new OrgWhere();
			if(CollectionUtils.isEmpty(strCon.getStatuss())){
				List<String> ss = new ArrayList<>();
				ss.add(DataStatusType.NORMAL.getCode());
				strCon.setStatuss(ss);
			}
			strCon.setSqlOrder("t.org_id != '"+UserUtil.getLoginUser().getOrgId()+"',t.create_time");
			return orgService.findAllListOrgs(strCon);
		}else {
			return new ArrayList<OrgVO>();
		}
		//return orgDao.listAll();
	}
	
	@GetMapping("/all")
	@ApiOperation(value = "机构-所有机构列表")
	/*//@PreAuthorize("hasAuthority('sys:org:query')")*/
	public List<OrgVO> ListAll(String keys,Boolean all) {
		LoginUser loginUser = UserUtil.getLoginUser();
		String orgId = loginUser.getOrgId();
		String orgIds = null;
		if(all != null && !all){
			orgIds = userService.getChildOrgIdsByOrgId(orgId);
		}
		return orgDao.allByOrgIds(orgIds,keys,orgId);
		//return orgDao.listAll();
	}

	@GetMapping("/listByTypeId/{id}")
	@ApiOperation(value = "机构-根据机构类型ID查询旗下机构列表")
	/*//@PreAuthorize("hasAuthority('sys:org:query')")*/
	public ApiResult<?> listbyTypeId(@PathVariable Long id) {
		if(id == null){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(orgDao.listbyTypeId(id));
	}

	@PostMapping
	@ApiOperation(value = "机构-跳过资源分配-保存")
	//@PreAuthorize("hasAuthority('sys:org:add') or hasAuthority('sys:org:edit') or hasAuthority('sys:org:addChild')")
	public ApiResult<?> save(@RequestBody Org org) {
		return orgService.save(org,false);
	}

	@PutMapping
	@ApiOperation(value = "机构-修改")
	//@PreAuthorize("hasAuthority('sys:org:edit')")
	public ApiResult<?> update(@RequestBody Org org) {
		if (StringUtilsV2.isBlank(org.getOrgId())) {
			return ApiResult.error("要修改的机构ID不能为空");
		}
		return orgService.save(org,false);
	}
	@GetMapping("/{id}")
	@ApiOperation(value = "机构-根据id获取")
	//@PreAuthorize("hasAuthority('sys:org:query')")
	public ApiResult<?> get(@PathVariable String id) {
		if(StringUtilsV2.isBlank(id)){
			return ApiResult.error("要查询的id不能为空");
		}
		
		return ApiResult.data(orgService.getOne(id, null));
	}

	@GetMapping("/idnamebytype/{typeId}")
	@ApiOperation(value = "机构-根据机构类型获取所有机构IDName")
	//@PreAuthorize("hasAuthority('sys:org:query')")
	public ApiResult<?> getOrgList(@PathVariable Long typeId) {
		if(typeId == null){
			return ApiResult.error("要查询的id不能为空");
		}
    	return ApiResult.data(orgDao.getShortOrgByType(typeId));
	}

	@GetMapping("/allorgtype")
	@ApiOperation(value = "机构-获取所有机构类型")
	//@PreAuthorize("hasAuthority('sys:org:query')")
	public List<KeyIdName> getOrgType() {
		return orgDao.getOrgType();
	}

	

	@PostMapping("/list")
	@ApiOperation(value = "机构-机构列表")
	//@PreAuthorize("hasAuthority('sys:org:query')")
	public PageInfo<OrgVO> LogListNew(@RequestBody OrgWhere strCon) {
		strCon.setSqlOrder("t.org_id != '"+UserUtil.getLoginUser().getOrgId()+"',t.create_time desc");
		return orgService.findAllOrgs(strCon);
	}
	
	@PostMapping("/select/list")
	@ApiOperation(value = "机构-机构列表")
	public PageInfo<OrgVO> LogListNewSelect(@RequestBody OrgWhere strCon) {
		if(CollectionUtils.isEmpty(strCon.getStatuss())){
			List<String> ss = new ArrayList<>();
			ss.add(DataStatusType.NORMAL.getCode());
			strCon.setStatuss(ss);
		}
		strCon.setSqlOrder("t.org_id != '"+UserUtil.getLoginUser().getOrgId()+"',t.create_time");
		return orgService.findAllOrgs(strCon);
	}

	@LogAnnotation
	@DeleteMapping("/delete/{id}")
	@ApiOperation(value = "机构-删除")
	//@PreAuthorize("hasAuthority('sys:org:del')")
	public ApiResult<?> delete(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("机构ID不能为空");
		}
		if(id.equals("1")){
			return ApiResult.error("系统机构不能删除");
		}
		ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2"), id);
		if(!checkAr.isSuccess()){
			return checkAr;
		}
		LoginUser user = UserUtil.getLoginUser();
		if(id.equals(user.getOrgId())){
			return ApiResult.error("用户不能删除自己的所属机构");
		}
		//下面有部门
		int childDepCount = depDao.countByOrgId(id);
		if(childDepCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+childDepCount+"个部门");
		}
		//下面有子机构
		int childOrgCount = orgDao.childOrgCountByParendId(id);
		if(childOrgCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+childOrgCount+"个子机构");
		}
		//下面有用户
		int userCount = userDao.countByOrgId(id);
		if(userCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+userCount+"个用户");
		}
		//下面有角色
		int childRoleCount = roleDao.countByOrgId(id);
		if(childRoleCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+childRoleCount+"个角色");
		}
		orgDao.delete(id);
		return ApiResult.ok();
	}

	@LogAnnotation
	@DeleteMapping("/{id}")
	@ApiOperation(value = "机构-逻辑删除")
	//@PreAuthorize("hasAuthority('sys:org:del')")
	public ApiResult<?> deleteEditStatus(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("机构ID不能为空");
		}
		if(id.equals("1")){
			return ApiResult.error("系统机构不能删除");
		}
		ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2"), id);
		if(!checkAr.isSuccess()){
			return checkAr;
		}
		LoginUser user = UserUtil.getLoginUser();
		if(id.equals(user.getOrgId())){
			return ApiResult.error("用户不能删除自己的所属机构");
		}
		//下面有部门
		int childDepCount = depDao.countByOrgId(id);
		if(childDepCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+childDepCount+"个部门");
		}
		//下面有子机构
		int childOrgCount = orgDao.childOrgCountByParendId(id);
		if(childOrgCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+childOrgCount+"个子机构");
		}
		//下面有用户
		int userCount = userDao.countByOrgId(id);
		if(userCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+userCount+"个用户");
		}
		//下面有角色
		int childRoleCount = roleDao.countByOrgId(id);
		if(childRoleCount > 0){
			return ApiResult.error("不能删除该机构，机构下面有"+childRoleCount+"个角色");
		}
		orgDao.updateStatus(Arrays.asList(id), Constant.DATA_STATUS_DELETE);
		return ApiResult.ok();
	}

	@LogAnnotation
	@DeleteMapping("/stop/{id}")
	@ApiOperation(value = "机构-停用")
	//@PreAuthorize("hasAuthority('sys:org:stop')")
	public ApiResult<?> stop(@PathVariable String id) {
		if (StringUtilsV2.isBlank(id)) {
			return ApiResult.error("机构ID不能为空");
		}
		if(id.equals("1")){
			return ApiResult.error("系统机构不能停用");
		}
		ApiResult<?> checkAr = CheckIdUtil.checkId(Arrays.asList("1","2"), id);
		if(!checkAr.isSuccess()){
			return checkAr;
		}
		//下面有部门
		int childDepCount = depDao.countByOrgId(id);
		if(childDepCount > 0){
			return ApiResult.error("不能停用该机构，机构下面有"+childDepCount+"个部门");
		}
		//下面有子机构
		int childOrgCount = orgDao.childOrgCountByParendId(id);
		if(childOrgCount > 0){
			return ApiResult.error("不能停用该机构，机构下面有"+childOrgCount+"个子机构");
		}
		//下面有用户
		int userCount = userDao.countByOrgId(id);
		if(userCount > 0){
			return ApiResult.error("不能停用该机构，机构下面有"+userCount+"个用户");
		}
		//下面有角色
		int childRoleCount = roleDao.countByOrgId(id);
		if(childRoleCount > 0){
			return ApiResult.error("不能停用该机构，机构下面有"+childRoleCount+"个角色");
		}
		orgDao.updateStatus(Arrays.asList(id), Constant.DATA_STATUS_TYPE_STOP);
		return ApiResult.ok();
	}

	@GetMapping("/listByOrgName")
	@ApiOperation(value = "机构-根据机构名查询机构列表")
	//@PreAuthorize("hasAuthority('sys:org:query')")
	public List<Map<String, Object>> listByOrgName(String orgName) {
		if (StringUtilsV2.isNotBlank(orgName)) {
			return orgDao.listByOrgName(orgName);
		}
		return orgDao.listAllMap();
	}
	
	@GetMapping("/web/logo")
	@ApiOperation(value = "机构-查询logo")
	public ApiResult<?> logo(String oid) {
		OrgOneVO org = null;
		Map<String, String> map = new HashMap<String, String>();
		if(StringUtilsV2.isBlank(oid)){
			LoginUser user = UserUtil.getLoginUser();
			String orgId;
			if(user != null) {
				orgId = user.getOrgId();
			}else {
				orgId = Constant.PLATFORM_ORG_ID;
			}
			org = orgService.getOne(orgId, null);
		}else {
			org = orgService.getOne(null, CommUtil.null2Long(oid));
			if(org == null) {
				org = orgService.getOne(Constant.PLATFORM_ORG_ID, null);
			}
		}
		if(org != null) {
			map.put("webLoginLogoAll", org.getWebLoginLogoAll());
			map.put("webLogoAll", org.getWebLogoAll()); 
			map.put("webTitle", org.getWebTitle());
		}else {
			map.put("webLoginLogoAll", Constant.PLATFORM_WEB_LOGIN_LOGO);
			map.put("webLogoAll", Constant.PLATFORM_WEB_LOGO);
			map.put("webTitle", Constant.PLATFORM_WEB_TITLE);
		}
		return ApiResult.data(map);
	}
	@PostMapping("/list/like")
	@ApiOperation(value = "机构-类型模糊查询")
	public ApiResult<?> getOrgsByTypeOrLike(@RequestBody OrgWhere where){
		if(CollectionUtils.isEmpty(where.getStatuss())){
			List<String> ss = new ArrayList<>();
			ss.add(DataStatusType.NORMAL.getCode());
			where.setStatuss(ss);
		}
		where.setSqlOrder("t.org_id != '"+UserUtil.getLoginUser().getOrgId()+"',t.create_time desc");
		
		return ApiResult.data(orgDao.getOrgsByTypeOrLike(where));
	}
	
	@GetMapping
	@ApiOperation(value = "机构列表-分页-v2")
	@Original
	public PageTableResponse LogListNew(PageTableRequest  strCon) {
		OrgWhere where = new OrgWhere(strCon);
		//userService.setOrgIdAndRoleIds(where,"sys:role:query");
		PageHelper.startPage(where.getOffset(), where.getLimit());
		if (StringUtilsV2.isBlank(where.getSqlOrder())) {
			where.setSqlOrder("t.create_time desc");
		}
		PageHelper.orderBy(where.getSqlOrder());
		List<OrgVO> log = orgDao.OrgList(where);
		PageInfo<OrgVO> result = new PageInfo<OrgVO>(log);
		return new PageTableHandler(new PageTableHandler.CountHandler() {
			@Override
			public int count(PageTableRequest request) {
				return CommUtil.null2Int(result.getTotal());
			}
		}, new PageTableHandler.ListHandler() {
			@Override
			public List<OrgVO> list(PageTableRequest request) {
				return result.getList();
			}
		}).handle(strCon);
		//return PageInfo<SysLogs> list = sysLogService.findAllLogs(new LogWhere(strCon));
	}
}
